"use client";

import easyFetch from "@/client/api/easyfetch";
import { useToast } from "@/components/ui/use-toast";
import { useRouter } from "next/navigation";
import { type Post } from "@prisma/client";
import PostEditorForm, { PostEditorFormValues } from "@/components/post-editor-form";

export default function EditorArea({ post }: { post: Post }) {
  const { toast } = useToast();
  const router = useRouter();

  const save = (values: PostEditorFormValues) =>
    (async () => {
      const result = await easyFetch.put<{ postId: string }>(`/api/posts/${post.id}`, {
        body: { ...values, contentType: "md" },
      });
      if (result.ok) {
        toast({ description: "Succeed!" });
        router.push(`/posts/${result.data.postId}`);
      } else {
        toast({ description: result.message });
      }
    })();

  return (
    <PostEditorForm
      initValues={{
        content: post.content,
        title: post.title,
        personal: post.personal,
      }}
      onSave={save}
    />
  );
}
